package com.ljyh.cygnus.serve

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.os.Build
import android.os.IBinder
import android.telephony.TelephonyManager
import android.util.Log
import androidx.core.app.NotificationCompat
import com.ljyh.cygnus.R
import com.ljyh.cygnus.utils.PolicyManager
import com.ljyh.cygnus.utils.RootCommandExecutor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch


class DevicePolicyService : Service() {

    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private var mobileDataMonitorJob: Job? = null
    companion object {
        const val ACTION_START = "com.yourapp.ACTION_START_WIFI_MONITORING"
        const val ACTION_STOP = "com.yourapp.ACTION_STOP_WIFI_MONITORING"
        private const val NOTIFICATION_CHANNEL_ID = "WifiMonitorChannel"
        private const val NOTIFICATION_ID = 101
    }

    // 广播接收器，用于监听WLAN状态变化
    private val wifiStateReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action != WifiManager.WIFI_STATE_CHANGED_ACTION) return

            val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
            val wifiPolicy = PolicyManager.getWifiPolicy(context)
            val isActuallyOn = (wifiState == WifiManager.WIFI_STATE_ENABLED || wifiState == WifiManager.WIFI_STATE_ENABLING)

            if (wifiPolicy == PolicyManager.POLICY_DISABLED && isActuallyOn) {
                Log.d("DevicePolicyService", "WLAN policy is DISABLED, but Wi-Fi is ON. Turning it OFF.")
                executeRootCommand("svc wifi disable")
            }
        }
    }



    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        // 注册广播接收器
        registerReceiver(wifiStateReceiver, IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION))
        registerReceiver(hotspotStateReceiver, IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED"))
    }

    private fun executeRootCommand(vararg commands: String) {
        serviceScope.launch {
            try {
                val result = RootCommandExecutor.execute(*commands)
                if (!result.isSuccess) {
                    Log.e("WifiMonitor", "Failed to execute 'svc wifi disable': ${result.stderr}")
                } else {
                    Log.d("WifiMonitor", "'svc wifi disable' executed successfully.")
                }
            } catch (e: Exception) {
                Log.e("WifiMonitor", "Exception while executing command", e)
            }
        }
    }

    // 2. 移动热点状态接收器 (新增)
    private val hotspotStateReceiver = object : BroadcastReceiver() {
        private val WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED"
        private val EXTRA_WIFI_AP_STATE = "wifi_state"
        private val WIFI_AP_STATE_ENABLING = 12
        private val WIFI_AP_STATE_ENABLED = 13

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action != WIFI_AP_STATE_CHANGED_ACTION) return

            val policy = PolicyManager.getHotspotPolicy(context)
            val wlan = PolicyManager.getWifiPolicy(context)
            if (policy == PolicyManager.POLICY_DISABLED) {
                val hotspotState = intent.getIntExtra(EXTRA_WIFI_AP_STATE, 0)
                val isHotspotOn = (hotspotState == WIFI_AP_STATE_ENABLING || hotspotState == WIFI_AP_STATE_ENABLED)

                if (isHotspotOn) {
                    Log.d("DevicePolicyService", "Hotspot Enforcer: Hotspot is ON against policy. Disabling Wi-Fi hardware.")
                    // 唯一职责：关闭硬件。WLAN监控器会负责善后。
                    executeRootCommand("svc wifi enable","svc wifi disable")
                    if(wlan == PolicyManager.POLICY_ENABLED){
                        executeRootCommand("svc wifi enable")
                    }

                }
            } else if (policy == PolicyManager.POLICY_RESTRICTED) {
                // “受限”策略依然使用防火墙，因为它不要求关闭热点
                Log.d("DevicePolicyService", "Hotspot is ON and policy is RESTRICTED. Enforcing firewall block.")
                val ensureBlockCommand = "iptables -D FORWARD -j DROP || true; iptables -I FORWARD 1 -j DROP"
                executeRootCommand(ensureBlockCommand)
            }
        }

    }

    // 流量数据监控

    private fun startMobileDataMonitoring() {
        // 如果已经在运行，先停止旧的
        mobileDataMonitorJob?.cancel()
        mobileDataMonitorJob = serviceScope.launch  {

            while (isActive) { // isActive 会在 scope 被 cancel 时变为 false
                // 只有在“禁用”策略下才执行检查

                if (PolicyManager.getMobileDataPolicy(this@DevicePolicyService) == PolicyManager.POLICY_DISABLED) {
                    // 检查数据流量是否开启 (1=开启, 0=关闭)
                    val result = RootCommandExecutor.execute("dumpsys phone | grep -E -q 'mDataConnectionState=2|DataState=CONNECTED|mDataEnabled=true|\"android:255\"'")
                    Log.d("DevicePolicyService", "disable check result =>${result.result.out}")
                    if (result.isSuccess && result.result.out.firstOrNull()?.trim()== "1") {

                        Log.d("DevicePolicyService", "Mobile data policy is DISABLED. Turning data off.")
                        executeRootCommand("svc data disable")
                    }
                }else if(PolicyManager.getMobileDataPolicy(this@DevicePolicyService) == PolicyManager.POLICY_ENABLED){
                    val result = RootCommandExecutor.execute("dumpsys phone | grep -E -q 'mDataConnectionState=2|DataState=CONNECTED|mDataEnabled=true|\"android:258\"'")
                    Log.d("DevicePolicyService", "enable check result =>${result.result.out}")
                    if (result.isSuccess && result.result.out.firstOrNull()?.trim()== "0") {

                        executeRootCommand("svc data enable")
                    }
                }
                // 每3秒检查一次
                delay(3000)
            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        startForeground(NOTIFICATION_ID, createNotification())

        // 启动数据流量监控轮询
//        startMobileDataMonitoring()

        return START_STICKY
    }


    override fun onBind(intent: Intent?): IBinder? {
        return null // 我们不使用绑定服务
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("设备安全管控")
            .setContentText("管控策略正在执行中...")
            .setSmallIcon(R.drawable.ic_launcher_background) // 请替换为您自己的图标
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "WiFi Monitoring Service Channel",
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(serviceChannel)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.d("DevicePolicyService", "Service Destroyed.")
        // 注销所有接收器
        unregisterReceiver(wifiStateReceiver)
        unregisterReceiver(hotspotStateReceiver)
        // 停止所有协程任务
        serviceScope.cancel()
    }

}